package com.base.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.base.po.voip.DialogBox;
import com.base.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.base.comm.CommContent;
import com.base.helper.VosHelper;
import com.base.po.param.InfoCustomers;
import com.base.po.param.VosModelList;
import com.base.po.sqlparam.UsersExamplePage;
import com.base.po.voip.Smsconfigs;
import com.base.po.voip.SmsconfigsExample;
import com.base.po.voip.Users;
import com.base.po.voip.UsersExample.Criteria;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.Page;
import com.base.utils.PasswordUtils;

/**
 * admin管理系统控制器
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class content_oemguanli {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private UsersService usersService;
	@Autowired
	private SmsconfigsService smsconfigsService;// 短信配置
	@Autowired
	private CallbackinfoesService callbackinfoesService;// 话单记录
	@Autowired
	private DialogBoxService dialogBoxService;

	// OEM管理
	@RequestMapping("/content_oemguanliOld")
	public ModelAndView indexOld(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		UsersExamplePage examplePage = new UsersExamplePage();
		examplePage.setOrderByClause("CreateTime");
		examplePage.pagesize = 10;
		examplePage.start = 0;
		examplePage.rows = examplePage.pagesize;// 设置首次分页
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		List<Users> users = null;
		Criteria criteria = examplePage.createCriteria();
		switch (adminUsergrade) {
		case 0:
			examplePage.getOredCriteria().add(criteria.andRoleBetween(0, 1));
			break;
		case 1:
			examplePage.getOredCriteria().add(criteria.andRoleEqualTo(1).andParentidEqualTo(adminUserId));
			break;
		}
		/*
		 * 设置分页
		 */
		int totlenum = usersService.countByExample(examplePage);// 页面总数
		request.setAttribute("totlenum", totlenum);// 传入session中
		request.setAttribute("curPage", 1);// 传入session中
		users = usersService.selectByExamplePage(examplePage);
		
		if (users != null) {
			for (Users u : users) {
				// 设置剩余短信
				SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
				smsconfigsExample.getOredCriteria().add(
						smsconfigsExample.createCriteria().andAgentidEqualTo(u.getId()).andDatastatusEqualTo(true));
				List<Smsconfigs> sms = smsconfigsService.selectByExample(smsconfigsExample);
				if (sms != null && sms.size() > 0) {
					u.setAppstore(sms.get(0).getCount() + "");
				} else {
					u.setAppstore("0");
				}
				DecimalFormat df = new DecimalFormat("#0.00");
				// 设计系统消耗
				BigDecimal xh = callbackinfoesService.sumOmoneyParentID(u.getId());
				if (xh == null) {
					u.setKeypath("0");
				} else {
					u.setKeypath(df.format(xh) + "");
				}
				u.setBlance(new BigDecimal(df.format(u.getBlance())));
				//TODO 设置话费余额，以及透支
				/**
				 * 测试
				 * 
				 * */
				
				try {
					String results = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "']}");
					String result1 = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "j']}");
					VosModelList v1 = GsonUtil.getObject(results, VosModelList.class);
					VosModelList v2 = GsonUtil.getObject(result1, VosModelList.class);
					if (v2 != null && v2.infoCustomers.length != 0 && v1 != null && v1.infoCustomers.length != 0) {
						InfoCustomers info2 = v2.infoCustomers[0];
						InfoCustomers info1 = v1.infoCustomers[0];
						u.setLinebalance(new BigDecimal(new DecimalFormat("0.00").format(info2.getMoney())));// 线路费
						u.setOverdraft(info2.getLimitMoney().intValue());// 透支
						// TODO
//						u.setFreeroute(info1.getFeeRateGroup());// 费率，数据库中已经保存
					} else {
						u.setLinebalance(new BigDecimal(0.00));
						u.setOneagent("0.00");
					}
				} catch (Exception e) {
					u.setLinebalance(new BigDecimal(0.00));
					u.setOneagent("0.00");
				}
				
				u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
			}
			// 设置页面进行跳转
			modelAndView.setViewName("jsp/content_oemguanli");
			request.setAttribute("auth", 4);
			request.setAttribute("list", users);
			return modelAndView;
		}
		String usernamesys = (String) request.getSession().getAttribute("useracc");
		logsService.insert(CommContent.TYPE_SYS, CommContent.LOGS_READ + "流量代理商信息", usernamesys, true,
				IP.getIpAddr(request));
		modelAndView.setViewName("jsp/datanotfound");
		return modelAndView;
	}

	@RequestMapping("/selectOemOld")
	public ModelAndView selectOemOld(HttpServletRequest request, String id, String username, Integer datastatus,
			Integer curPage) throws Exception {
		// 设置session缓存
		if (curPage == null) {
			if (request.getSession().getAttribute("curPage") != null) {
				curPage = (Integer) request.getSession().getAttribute("curPage");
			} else {
				curPage = 1;
			}
		}
		if (id == null) {
			if (request.getSession().getAttribute("id") != null) {
				id = (String) request.getSession().getAttribute("id");
			}
		}
		if (username == null) {
			if (request.getSession().getAttribute("username") != null) {
				username = (String) request.getSession().getAttribute("username");
			}
		}
		if (datastatus == null) {
			if (request.getSession().getAttribute("datastatus") != null) {
				datastatus = (Integer) request.getSession().getAttribute("datastatus");
			} else {
				datastatus = 0;
			}
		}
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		UsersExamplePage examplePage = new UsersExamplePage();
		examplePage.setOrderByClause("CreateTime");
		examplePage.pagesize = 10;
		examplePage.start = (curPage - 1) * examplePage.pagesize;
		examplePage.rows = examplePage.pagesize;// 设置首次分页
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		List<Users> users = null;
		Criteria criteria = examplePage.createCriteria();
		// 条件筛选
		if (id != null && !id.equals("")) {
			request.setAttribute("id", id);
			criteria = criteria.andIdEqualTo(id);
			examplePage.getOredCriteria().add(criteria);
		}
		if (username != null && !username.equals("")) {
			request.setAttribute("username", username);
			criteria = criteria.andUsernameLike("%" + username + "%");
			examplePage.getOredCriteria().add(criteria);
		}
		if (datastatus != null) {
			// 判断当前可用性
			switch (datastatus) {
			case 2:
				examplePage.getOredCriteria().add(criteria.andDatastatusEqualTo(false));
				break;
			case 1:
				examplePage.getOredCriteria().add(criteria.andDatastatusEqualTo(true));
				break;
			case 0:
				break;
			}
		}
		request.setAttribute("datastatus", datastatus);
		switch (adminUsergrade) {
		case 0:
			examplePage.getOredCriteria().add(criteria.andRoleBetween(0, 1));
			break;

		case 1:
			examplePage.getOredCriteria().add(criteria.andRoleEqualTo(1).andParentidEqualTo(adminUserId));
			break;
		}

		/*
		 * 设置分页
		 */
		int totlenum = usersService.countByExample(examplePage);// 页面总数
		request.setAttribute("totlenum", totlenum);// 总数据传入session中
		request.setAttribute("curPage", curPage);// 当前页面传入session中
		users = usersService.selectByExamplePage(examplePage);
		if (users != null) {
			for (Users u : users) {
				// 设置剩余短信
				SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
				smsconfigsExample.getOredCriteria().add(
						smsconfigsExample.createCriteria().andAgentidEqualTo(u.getId()).andDatastatusEqualTo(true));
				List<Smsconfigs> sms = smsconfigsService.selectByExample(smsconfigsExample);
				if (sms != null && sms.size() > 0) {
					u.setAppstore(sms.get(0).getCount() + "");
				} else {
					u.setAppstore("0");
				}
				DecimalFormat df = new DecimalFormat("#0.00");
				// 设置系统消耗
				BigDecimal xh = callbackinfoesService.sumOmoneyParentID(u.getId());
				if (xh == null) {
					u.setKeypath("0");
				} else {
					u.setKeypath(df.format(xh) + "");
				}
				u.setBlance(new BigDecimal(df.format(u.getBlance())));
				//TODO 设置话费余额，以及透支
				String results = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "']}");
				String result1 = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "j']}");
				VosModelList v1 = GsonUtil.getObject(results, VosModelList.class);
				VosModelList v2 = GsonUtil.getObject(result1, VosModelList.class);
				if (v2 != null && v2.infoCustomers.length != 0 && v1 != null && v1.infoCustomers.length != 0) {
					InfoCustomers info2 = v2.infoCustomers[0];
					InfoCustomers info1 = v1.infoCustomers[0];
					u.setLinebalance(new BigDecimal(new DecimalFormat("0.00").format(info2.getMoney())));// 线路费
					u.setOverdraft(info2.getLimitMoney().intValue());// 透支
					// TODO
//					u.setFreeroute(info1.getFeeRateGroup());// 费率，数据库中已经保存
				} else {
					u.setLinebalance(new BigDecimal(0.00));
					u.setOneagent("0.00");
				}
				u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
			}
			// 设置页面进行跳转
			modelAndView.setViewName("jsp/content_oemguanli");
			request.setAttribute("auth", datastatus);
			request.setAttribute("list", users);
			return modelAndView;
		}
		modelAndView.setViewName("jsp/datanotfound");
		return modelAndView;
	}
	
	@RequestMapping("/content_oemguanli")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		Page page = new Page();
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		// 登陆商家
		Users user = usersService.selectByPrimaryKey(adminUserId);
		List<Users> users = null;
		switch (adminUsergrade) {
		case 0:
			page.setCurrentPageNo(1);
			page.setRecordTotal(usersService.countOEMByAll(null, null));
			users = usersService.selectOEMByAll(page, null, null);
			break;
		case 1:
			page.setCurrentPageNo(1);
			page.setRecordTotal(usersService.countOEMByParentID(adminUserId, null, null));
			users = usersService.selectOEMByParentID(page, adminUserId, null, null);
			break;
		}
		/*
		 * 设置分页
		 */
		int totlenum = page.getRecordTotal();// 页面总数
		request.setAttribute("totlenum", totlenum);// 传入session中
		request.setAttribute("curPage", page.getCurrentPageNo());// 传入session中
		
		if (users != null) {
			for (Users u : users) {
				// 设置剩余短信
				List<Smsconfigs> sms = smsconfigsService.selectByAgentIdAll(u.getId());
				if (sms != null && sms.size() > 0) {
					u.setAppstore(sms.get(0).getCount() + "");
				} else {
					u.setAppstore("0");
				}
				DecimalFormat df = new DecimalFormat("#0.00");
				// 设计系统消耗
				BigDecimal xh = callbackinfoesService.sumOmoneyParentID(u.getId());
				if (xh == null) {
					u.setKeypath("0");
				} else {
					u.setKeypath(df.format(xh) + "");
				}
				u.setBlance(new BigDecimal(df.format(u.getBlance())));
				//TODO 设置话费余额，以及透支
				/**
				 * 测试
				 * 
				 * */
			   try {
					String results = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "']}");
					String result1 = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "j']}");
					VosModelList v1 = GsonUtil.getObject(results, VosModelList.class);
					VosModelList v2 = GsonUtil.getObject(result1, VosModelList.class);
					if (v2 != null && v2.infoCustomers.length != 0 && v1 != null && v1.infoCustomers.length != 0) {
						InfoCustomers info2 = v2.infoCustomers[0];
						InfoCustomers info1 = v1.infoCustomers[0];
						u.setLinebalance(new BigDecimal(new DecimalFormat("0.00").format(info2.getMoney())));// 线路费
						u.setOverdraft(info2.getLimitMoney().intValue());// 透支
						// TODO
//						u.setFreeroute(info1.getFeeRateGroup());// 费率，数据库中已经保存
					} else {
						u.setLinebalance(new BigDecimal(0.00));
						u.setOneagent("0.00");
					}
				} catch (Exception e) {
					u.setLinebalance(new BigDecimal(0.00));
					u.setOneagent("0.00");
				}

				u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码

				List<DialogBox> dialogBox = dialogBoxService.selectByParentId(u.getId());
				if (dialogBox != null && dialogBox.size() > 0){
					u.setDialogboxid(dialogBox.get(0).getId());
				}
			}
			// 设置页面进行跳转
			modelAndView.setViewName("jsp/content_oemguanli");
			request.setAttribute("auth", 4);
			request.setAttribute("list", users);
			request.setAttribute("adminUser", user);
			request.setAttribute("adminUserId", adminUserId);
			return modelAndView;
		}
		String usernamesys = (String) request.getSession().getAttribute("useracc");
		logsService.insert(CommContent.TYPE_SYS, CommContent.LOGS_READ + "流量代理商信息", usernamesys, true,
				IP.getIpAddr(request));
		modelAndView.setViewName("jsp/datanotfound");
		return modelAndView;
	}
	
	@RequestMapping("/selectOem")
	public ModelAndView selectOem(HttpServletRequest request, String id, String username, Integer datastatus,
			Integer curPage) throws Exception {
		// 设置session缓存
		if (curPage == null) {
			if (request.getSession().getAttribute("curPage") != null) {
				curPage = (Integer) request.getSession().getAttribute("curPage");
			} else {
				curPage = 1;
			}
		}
		if (id == null) {
			if (request.getSession().getAttribute("id") != null) {
				id = (String) request.getSession().getAttribute("id");
			}
		}
		if (username == null) {
			if (request.getSession().getAttribute("username") != null) {
				username = (String) request.getSession().getAttribute("username");
			}
		}
		if (datastatus == null) {
			if (request.getSession().getAttribute("datastatus") != null) {
				datastatus = (Integer) request.getSession().getAttribute("datastatus");
			} else {
				datastatus = 0;
			}
		}
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		Page page = new Page();
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		// 登陆商家
		Users user = usersService.selectByPrimaryKey(adminUserId);
		List<Users> users = null;
		
		String pName = null;
		Boolean status = null;
		// 条件筛选
		if (username != null && !username.equals("")) {
			pName = username;
		}
		if (datastatus != null) {
			// 判断当前可用性
			switch (datastatus) {
			case 2:
				status = false;
				break;
			case 1:
				status = true; 
				break;
			case 0:
				break;
			}
		}
		request.setAttribute("datastatus", datastatus);
		switch (adminUsergrade) {
		case 0:
			page.setCurrentPageNo(curPage);
			page.setRecordTotal(usersService.countOEMByAll(pName, status));
			users = usersService.selectOEMByAll(page, pName, status);
			break;

		case 1:
			page.setCurrentPageNo(curPage);
			page.setRecordTotal(usersService.countOEMByParentID(adminUserId, pName, status));
			users = usersService.selectOEMByParentID(page, adminUserId, pName, status);
			break;
		}

		/*
		 * 设置分页
		 */
		int totlenum = page.getRecordTotal();// 页面总数
		request.setAttribute("totlenum", totlenum);// 总数据传入session中
		request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中
		
		if (users != null) {
			for (Users u : users) {
				// 设置剩余短信
				List<Smsconfigs> sms = smsconfigsService.selectByAgentIdAll(u.getId());
				if (sms != null && sms.size() > 0) {
					u.setAppstore(sms.get(0).getCount() + "");
				} else {
					u.setAppstore("0");
				}
				DecimalFormat df = new DecimalFormat("#0.00");
				// 设置系统消耗
				BigDecimal xh = callbackinfoesService.sumOmoneyParentID(u.getId());
				if (xh == null) {
					u.setKeypath("0");
				} else {
					u.setKeypath(df.format(xh) + "");
				}
				u.setBlance(new BigDecimal(df.format(u.getBlance())));
				//TODO 设置话费余额，以及透支
				try {
					String results = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "']}");
					String result1 = VosHelper.GetVosAccount("{accounts:['" + u.getUsername() + "j']}");
					VosModelList v1 = GsonUtil.getObject(results, VosModelList.class);
					VosModelList v2 = GsonUtil.getObject(result1, VosModelList.class);
					if (v2 != null && v2.infoCustomers.length != 0 && v1 != null && v1.infoCustomers.length != 0) {
						InfoCustomers info2 = v2.infoCustomers[0];
						InfoCustomers info1 = v1.infoCustomers[0];
						u.setLinebalance(new BigDecimal(new DecimalFormat("0.00").format(info2.getMoney())));// 线路费
						u.setOverdraft(info2.getLimitMoney().intValue());// 透支
						// TODO
//						u.setFreeroute(info1.getFeeRateGroup());// 费率，数据库中已经保存
					} else {
						u.setLinebalance(new BigDecimal(0.00));
						u.setOneagent("0.00");
					}
				} catch (Exception e) {
					u.setLinebalance(new BigDecimal(0.00));
					u.setOneagent("0.00");
				}
				
				u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码

				List<DialogBox> dialogBox = dialogBoxService.selectByParentId(u.getId());
				if (dialogBox != null && dialogBox.size() > 0){
					u.setDialogboxid(dialogBox.get(0).getId());
				}
			}
			// 设置页面进行跳转
			modelAndView.setViewName("jsp/content_oemguanli");
			request.setAttribute("username", username);
			request.setAttribute("auth", datastatus);
			request.setAttribute("list", users);
			request.setAttribute("adminUser", user);
			request.setAttribute("adminUserId", adminUserId);
			return modelAndView;
		}
		modelAndView.setViewName("jsp/datanotfound");
		return modelAndView;
	}

}
